<template>
    <view>
        <!-- 自定义导航栏 -->
        <!-- <custom-navbar title="商品订单详情" backgroundColor="#ffffff" textColor="#000" :showBack="true" :isHomePage="false"></custom-navbar> -->
        <custom-navbar title="商品订单详情" backgroundColor="#ffffff" textColor="#000" :showBack="true" :isHomePage="false"></custom-navbar>
        <view class="shopDetail" :style="'height: calc(100vh - ' + navHeight + 'px - 172rpx);'">
            <!-- 订单状态 -->
            <view class="shopDetail_status">
                <image src="https://image.shengxuankj.com/fronts/order_status_BG.png" mode="" />
                <view class="shopDetail_status_container">
                    <view class="shopDetail_status_container_info">
                        <text class="status" v-if="orderData.pay_status == 0">待支付</text>
                        <text class="status" v-if="orderData.pay_status == 1">已支付</text>
                        <!-- <text class="status" v-if="orderData.pay_status == 1 && orderData.is_used == 0">待入住</text> -->
                        <!-- <text class="status" v-if="orderData.pay_status == 1 && orderData.is_used == 1">已入住</text> -->
                        <text class="status" v-if="orderData.pay_status == 2">订单已取消</text>
                        <text class="status" v-if="orderData.pay_status == 1 && orderData.refund_status == 1">已退款</text>
                        <!-- <text v-if="orderData.countdown" class="time">剩余{{ orderData.countdown }}分钟</text> -->
                    </view>
                    <view class="shopDetail_status_container_tips">{{ getStatusTips(orderData) }}</view>
                </view>
            </view>
            
            <!-- 商品列表 -->
            <view class="shopDetail_goods">
                <view class="shopDetail_goods_title">商品清单</view>
                <view class="shopDetail_goods_list">
                    <view v-for="(item, index) in orderData.goods_list || []" :key="index" class="goods_item">
                        <view class="goods_item_left">
                            <image :src="item.image || 'https://image.shengxuankj.com/fronts/goods_default.png'" mode="aspectFill" />
                        </view>
                        <view class="goods_item_right">
                            <view class="goods_item_title">{{ item.goods_name }}</view>
                            <!-- <view class="goods_item_spec" v-if="item.spec">{{ item.spec }}</view> -->
                            <view class="goods_item_bottom">
                                <!-- <view class="goods_item_price">￥{{ item.price }}</view> -->
                                <view class="goods_item_total">￥{{ item.goods_money }}</view>
                                <view class="goods_item_quantity">x{{ item.number }}</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            
            <!-- 订单金额 -->
            <view class="shopDetail_amount">
                <view class="shopDetail_amount_item">
                    <text>商品总额</text>
                    <text>￥{{ orderData.order_amount }}</text>
                </view>
                <!-- <view class="shopDetail_amount_item" v-if="orderData.shipping_fee">
                    <text>运费</text>
                    <text>￥{{ orderData.shipping_fee }}</text>
                </view>
                <view class="shopDetail_amount_item" v-if="orderData.discount_amount">
                    <text>优惠金额</text>
                    <text class="discount">-￥{{ orderData.discount_amount }}</text>
                </view> -->
                <view class="shopDetail_amount_total">
                    <text>实付金额</text>
                    <text class="total_price">￥{{ orderData.order_amount }}</text>
                </view>
            </view>
            
            <!-- 收货信息 -->
            <!-- <view class="shopDetail_address" v-if="orderData.address">
                <view class="shopDetail_address_title">收货信息</view>
                <view class="shopDetail_address_info">
                    <view class="address_line">
                        <text class="name">{{ orderData.address.name }}</text>
                        <text class="phone">{{ orderData.address.phone }}</text>
                    </view>
                    <view class="address_detail">{{ orderData.address.detail }}</view>
                </view>
            </view> -->
            
            <!-- 订单信息 -->
            <view class="shopDetail_orderInfo">
                <view class="shopDetail_orderInfo_item">
                    <text>订单编号</text>
                    <text>{{ orderData.order_no || '394028475930282740843' }}</text>
                </view>
                <view class="shopDetail_orderInfo_item">
                    <text>下单时间</text>
                    <text>{{ orderData.create_time || '2025-07-16 12:23:28' }}</text>
                </view>
                <!-- <view class="shopDetail_orderInfo_item" v-if="orderData.pay_time">
                    <text>支付时间</text>
                    <text>{{ orderData.pay_time }}</text>
                </view>
                <view class="shopDetail_orderInfo_item" v-if="orderData.delivery_time">
                    <text>发货时间</text>
                    <text>{{ orderData.delivery_time }}</text>
                </view> -->
            </view>
            
            <!-- 底部操作按钮 -->
            <view class="shopDetail_footer">
                <view class="shopDetail_footer_left">
                    <!-- <text class="more" @tap="openMore">更多</text> -->
                    <up-button color="#999999" round custom-class="btn" @tap.native="cancelOrder" plain v-if="orderData.pay_status == 0">取消订单</up-button>
                    <up-button color="#999999" round custom-class="btn" @tap.native="cancelOrder" plain v-if="orderData.pay_status == 1 && orderData.is_used == 0 && orderData.return_status == 0">退款</up-button>
                </view>
                <view class="shopDetail_footer_right">
                    <up-button color="rgba(57, 97, 54, 1)" round custom-class="btn" @tap.native="goToPayPage" v-if="orderData.pay_status == 0">立即支付</up-button>
                    <!-- <up-button v-else-if="canConfirm()" color="rgba(57, 97, 54, 1)" round custom-class="btn" @tap.native="confirmReceive">确认收货</up-button> -->
                </view>
            </view>
        </view>
        
        <!-- 更多操作弹窗 -->
        <up-action-sheet
            :show="show"
            :actions="actions"
            cancel-text="取消"
            :close-on-click-overlay="true"
            :close-on-click-action="true"
            :safe-area-inset-bottom="true"
            :root-portal="true"
            :overlay="true"
            @close="close"
            @cancel="close"
            @click-overlay="close"
            @select="selectFun"
        />
    </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { orderGoodsDetailFun, orderGoodsCancelFun, payFun } from '@/api/port'

// 接口定义
interface GoodsItem {
    id: number
    name: string
    image: string
    price: number
    quantity: number
    spec?: string
}

interface OrderData {
    order_no: string
    status: number
    status_text: string
    countdown?: string
    goods_list: GoodsItem[]
    goods_amount: number
    shipping_fee?: number
    discount_amount?: number
    total_amount: number
    address?: {
        name: string
        phone: string
        detail: string
    }
    create_time: string
    pay_time?: string
    delivery_time?: string
}

interface Action {
    name: string
}

interface SelectEvent {
    detail: any
}

// 响应式数据
const show = ref<boolean>(false)
const actions = ref<Action[]>([
    { name: '联系客服' },
    { name: '查看物流' }
])
const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88)
const order_id = ref<any>()
const orderData = ref<OrderData>({})



// 计算商品总额
const calculateGoodsAmount = (): string => {
    const goodsList = orderData.value.goods_list.length > 0 ? orderData.value.goods_list : []
    const total = goodsList.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    return total.toFixed(2)
}

// 计算实付金额
const calculateTotalAmount = (): string => {
    const goodsAmount = parseFloat(calculateGoodsAmount())
    const shippingFee = orderData.value.shipping_fee || 0
    const discountAmount = orderData.value.discount_amount || 0
    return (goodsAmount + shippingFee - discountAmount).toFixed(2)
}

// 获取状态提示文字
const getStatusTips = (orderData: any): string => {
    const { pay_status, refund_status, is_used } = orderData
    if (pay_status === 0) {
        return '订单未支付，请在尽快进行支付，以免耽误您的旅程'
    }
    if (pay_status === 1) {
        return '订单已支付，请您按时到店'
    }
    if (pay_status === 2) {
        return '订单已取消，欢迎再次光临'
    }
    if (pay_status === 1 && refund_status === 1) {
        return '已退款，退款将在24小时内到账'
    }
}



const close = (): void => {
    show.value = false
}

const selectFun = (event: SelectEvent): void => {
    console.log(event.detail)
    close()
}

const goToPayPage = (): void => {
    requestWeChatPay()
    // uni.navigateTo({
    //     url: `/subpackage/shopPayPage/shopPayPage?orderId=${order_id.value}`
    // })
}
// 调用微信支付
const requestWeChatPay = async (): Promise<any> => {
    try {
        // 这里应该调用后端API获取支付参数
        // 模拟获取支付参数
        const res = await payFun({ order_id: order_id.value, from: 'goods_order', pay_way: '2' })
        console.log('res', res)
        const paymentParams: PaymentParams = {
            timeStamp: res.data.config.timeStamp,
            nonceStr: res.data.config.nonceStr,
            package: res.data.config.package,
            signType: res.data.config.signType,
            paySign: res.data.config.paySign
        }

        // 调用微信支付API
        return new Promise((resolve, reject) => {
            uni.requestPayment({
                ...paymentParams,
                success: (res: any) => {
                    console.log('支付成功:', res)
                    resolve(res)
                },
                fail: (err: any) => {
                    console.error('支付失败:', err)
                    if (err.errMsg === 'requestPayment:fail cancel') {
                        reject(new Error('用户取消支付'))
                    } else {
                        reject(new Error('支付失败: ' + err.errMsg))
                    }
                }
            })
        })
    } catch (error) {
        console.log('CatchClause', error)
        console.error('请求支付失败:', error)
        throw error
    }
}

const cancelOrder = async (): Promise<void> => {
    uni.showModal({
        title: '提示',
        content: '确定要取消订单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await orderGoodsCancelFun({ order_id: order_id.value })
                    if (result.code === 1) {
                        uni.showToast({
                            title: '订单已取消',
                            icon: 'success'
                        })
                        await getOrderDetail()
                    } else {
                        uni.showToast({
                            title: result.msg || '取消失败',
                            icon: 'error'
                        })
                    }
                } catch (error) {
                    uni.showToast({
                        title: '网络异常',
                        icon: 'error'
                    })
                }
            }
        }
    })
}

const confirmReceive = (): void => {
    uni.showModal({
        title: '提示',
        content: '确定已收到商品吗？',
        success: (res) => {
            if (res.confirm) {
                // 确认收货逻辑
                uni.showToast({
                    title: '确认收货成功',
                    icon: 'success'
                })
            }
        }
    })
}

// 获取订单详情
const getOrderDetail = async (): Promise<void> => {
    try {
        const res = await orderGoodsDetailFun({ id: order_id.value })
        console.log('获取订单详情成功:', res)
        if (res.code === 1 && res.data) {
            orderData.value = res.data
        }
    } catch (error) {
        console.error('获取订单详情失败:', error)
        // 使用模拟数据
    }
}

onLoad(async (options) => {
    order_id.value = options.id
    await getOrderDetail()
})
</script>

<style scoped>
/* 主容器 */
.shopDetail {
    width: 100%;
    background-color: #f5f5f5;
}

/* 订单状态 */
.shopDetail_status {
    width: 100%;
    position: relative;
}

.shopDetail_status image {
    width: 100%;
    height: 206rpx;
}

.shopDetail_status_container {
    position: absolute;
    top: 0;
    left: 0;
    width: 70%;
    height: 100%;
    padding: 30rpx;
    box-sizing: border-box;
}

.shopDetail_status_container_info {
    width: 100%;
    display: flex;
    align-items: baseline;
    justify-content: flex-start;
}

.shopDetail_status_container_info .status {
    font-size: 40rpx;
    font-weight: bold;
    letter-spacing: 0px;
    line-height: 57.92rpx;
    color: rgba(43, 48, 43, 1);
}

.shopDetail_status_container_info .time {
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 57.92rpx;
    color: rgba(255, 141, 26, 1);
    margin-left: 24rpx;
}

.shopDetail_status_container_tips {
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 32rpx;
    color: rgba(85, 85, 85, 1);
    margin-top: 10rpx;
}

/* 商品列表 */
.shopDetail_goods {
    width: calc(100% - 60rpx);
    margin: 30rpx auto 0;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-sizing: border-box;
}

.shopDetail_goods_title {
    font-size: 32rpx;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
    margin-bottom: 30rpx;
}

.goods_item {
    display: flex;
    align-items: flex-start;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.goods_item:last-child {
    border-bottom: none;
}

.goods_item_left {
    width: 120rpx;
    height: 120rpx;
    margin-right: 20rpx;
}

.goods_item_left image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
}

.goods_item_right {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.goods_item_title {
    font-size: 28rpx;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    line-height: 40rpx;
    margin-bottom: 8rpx;
}

.goods_item_spec {
    font-size: 24rpx;
    color: rgba(153, 153, 153, 1);
    margin-bottom: 16rpx;
}

.goods_item_bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.goods_item_price {
    font-size: 28rpx;
    font-weight: 600;
    color: rgba(255, 141, 26, 1);
}

.goods_item_quantity {
    font-size: 24rpx;
    color: rgba(153, 153, 153, 1);
}

.goods_item_total {
    font-size: 28rpx;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
}

/* 订单金额 */
.shopDetail_amount {
    width: calc(100% - 60rpx);
    margin: 30rpx auto 0;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-sizing: border-box;
}

.shopDetail_amount_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.shopDetail_amount_item:last-child {
    margin-bottom: 0;
}

.shopDetail_amount_item text:first-child {
    font-size: 28rpx;
    color: rgba(153, 153, 153, 1);
}

.shopDetail_amount_item text:last-child {
    font-size: 28rpx;
    color: rgba(51, 51, 51, 1);
}

.shopDetail_amount_item .discount {
    color: rgba(255, 141, 26, 1);
}

.shopDetail_amount_total {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;
}

.shopDetail_amount_total text:first-child {
    font-size: 32rpx;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
}

.shopDetail_amount_total .total_price {
    font-size: 36rpx;
    font-weight: bold;
    color: rgba(255, 141, 26, 1);
}

/* 收货信息 */
.shopDetail_address {
    width: calc(100% - 60rpx);
    margin: 30rpx auto 0;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-sizing: border-box;
}

.shopDetail_address_title {
    font-size: 32rpx;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
    margin-bottom: 20rpx;
}

.address_line {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;
}

.address_line .name {
    font-size: 28rpx;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    margin-right: 20rpx;
}

.address_line .phone {
    font-size: 28rpx;
    color: rgba(153, 153, 153, 1);
}

.address_detail {
    font-size: 28rpx;
    color: rgba(153, 153, 153, 1);
    line-height: 40rpx;
}

/* 订单信息 */
.shopDetail_orderInfo {
    width: calc(100% - 60rpx);
    margin: 30rpx auto 0;
    padding: 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    gap: 25rpx;
    background-color: #fff;
}

.shopDetail_orderInfo_item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.shopDetail_orderInfo_item text:nth-child(1) {
    width: 6em;
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 44rpx;
    color: rgba(153, 153, 153, 1);
}

.shopDetail_orderInfo_item text:nth-child(2) {
    width: calc(100% - 6em);
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 44rpx;
    color: rgba(51, 51, 51, 1);
}

/* 底部操作 */
.shopDetail_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 172rpx;
    padding: 24rpx 30rpx 0 34rpx;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    background-color: #ffffff;
    border-top: 1rpx solid #f0f0f0;
}

.shopDetail_footer_left {
    width: calc(100% - 385rpx - 24rpx);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0 24rpx;
}

.shopDetail_footer_left .more {
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(153, 153, 153, 1);
    width: 2em;
}

.shopDetail_footer_left .btn {
    margin: 0 !important;
    width: 197rpx;
    height: 80rpx;
}

.shopDetail_footer_right {
    width: 385rpx;
    height: 80rpx;
    margin-left: 24rpx;
}

.shopDetail_footer_right .btn {
    width: 100%;
    height: 100%;
    margin: 0 !important;
}
</style>